package com.b2c.erp.controller.system;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.b2c.entity.api.ApiResult;
import com.b2c.entity.api.ApiResultEnum;
import com.b2c.entity.DataRow;

@Controller
@RequestMapping("/system")
public class SqlBackupController {
    Logger log = LoggerFactory.getLogger(SqlBackupController.class);

    

    @RequestMapping(value = "/backup_mysql", method = RequestMethod.GET)
    public String backup(Model model, HttpServletRequest request) {
        String dir = System.getProperty("user.dir");
        log.info("读取到根目录："+dir);
        String path = dir + File.separator + "mysql" + File.separator;
        model.addAttribute("path", path);
        List<FileVo> backupList = new ArrayList<>();

        SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
	    FileTime t = null;

        // 读取文件夹文件
        final File folder = new File(path);
        if (!folder.exists() && !folder.isDirectory()) {
            folder.mkdirs();
            log.info("文件夹不存在，创建文件夹："+path);
        }

        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isDirectory() == false) {
                log.info("读取到文件："+fileEntry.getName());
                FileVo vo = new FileVo();
                vo.setName(fileEntry.getName());
                try {
                    t = Files.readAttributes(Paths.get(path + fileEntry.getName()), BasicFileAttributes.class).lastModifiedTime();
                    vo.setTime(dateFormat.format(t.toMillis()));
                    log.info("文件创建时间："+dateFormat.format(t.toMillis()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                backupList.add(vo);
            }
        }
        model.addAttribute("backupList", backupList);


        
	     
	     
		
	
        
        model.addAttribute("view", "backup");
        model.addAttribute("pView", "kc");

        return "system/backup_mysql";
    }

    @ResponseBody
    @RequestMapping(value = "/backup_select_ajax", method = RequestMethod.POST)
    public ApiResult<String> backupSelectAJAX(@RequestParam("excel") MultipartFile file, HttpServletRequest req) {
        String fileName = file.getOriginalFilename();

        return new ApiResult<>(ApiResultEnum.SUCCESS, "SUCCESS");
    }

    @ResponseBody
    @RequestMapping(value = "/backup_mysql_ajax", method = RequestMethod.POST)
    public ApiResult<String> backupAJAX(HttpServletRequest req,@RequestBody DataRow data) {
        String backupFolderPath = data.getString("path");
        // String[] s = getCommand("");

        // String dir = System.getProperty("user.dir");
        // String backupFolderPath = dir + File.separator + "mysql";

        File backupFolderFile = new File(backupFolderPath);
        if (!backupFolderFile.exists()) {
            // 如果目录不存在则创建文件
            backupFolderFile.mkdirs();
        }
        if (!backupFolderPath.endsWith(File.separator) && !backupFolderPath.endsWith("/")) {
            backupFolderPath = backupFolderPath + File.separator;
        }
        backupFolderPath = backupFolderPath.replace("\\", "/");
        SimpleDateFormat newsdf = new SimpleDateFormat("yyyyMMdd");
        String date = newsdf.format(new Date());

        String fileName = "mysql_backup_" + date + ".sql";
        String host = "127.0.0.1";
        String port = "3306";
        String userName = "root";
        String password = "123456";
        String database = "ecom";

        // 拼接执行命令
        String backupFilePath = backupFolderPath + fileName;
        StringBuilder sb = new StringBuilder();
        sb.append("mysqldump --opt ").append(" --add-drop-database ").append(" --add-drop-table ");
        sb.append(" -h").append(host).append(" -P").append(port).append(" -u").append(userName).append(" -p")
                .append(password);
        sb.append(" --result-file=").append(backupFilePath).append(" --default-character-set=utf8 ").append(database);
        // 调用外部执行 exe 文件的 Java API
        System.out.println("=======================开始执行备份命令===========================");
        System.out.println(sb.toString());
        try {
            Runtime r = Runtime.getRuntime();
            // Process process1 = r.exec(getCommand("cd C:/Program Files/MariaDB
            // 10.6/bin"));
            // int s1 = process1.waitFor();
            // Process process2 = r.exec(getCommand("ping 192.168.1.1"));
            // int s21= process2.waitFor();
            Process process = r.exec(getCommand(sb.toString()));
            // int s2= process.waitFor();
            if (process.waitFor() == 0) {
                // 0 表示线程正常终止
                System.out.println("数据已经备份到 " + backupFilePath + " 文件中");
                log.info("数据已经备份到 " + backupFilePath + " 文件中");

            } else {
                return new ApiResult<>(ApiResultEnum.SystemException, "运行错误，请检查命令是否正确");
            }
        } catch (Exception e) {

            return new ApiResult<>(ApiResultEnum.SystemException, "系统异常");
        }

        return new ApiResult<>(ApiResultEnum.SUCCESS, "数据已经备份到 " + backupFilePath + " 文件中");
    }

    private String[] getCommand(String command) {
        String os = System.getProperty("os.name");
        String shell = "/bin/bash";
        String c = "-c";
        if (os.toLowerCase().startsWith("win")) {
            shell = "cmd";
            c = "/c";
            // c = "C:/Program Files/MariaDB 10.6/bin/mysqldump";
        }
        String[] cmd = { shell, c, command };
        return cmd;
    }

}
